package com.lgj.gateway.jdbc;

import com.lgj.gateway.jdbc.model.GatewayRoute;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author guangjie.liao
 * @Date: 2022/10/25 08:45
 * @Description:
 */
@Repository
public class RouteRepository {
    @Resource
    private JdbcTemplate jdbcTemplate;

    private static String SELECT_FALL_ROUTE_SQL = "select * from gateway_route where status = 0";

    public List<GatewayRoute> selectAllRoute(){
        List<GatewayRoute> routeList = jdbcTemplate.query(SELECT_FALL_ROUTE_SQL, new RowMapper<GatewayRoute>() {
            @Override
            public GatewayRoute mapRow(ResultSet rs, int rowNum) throws SQLException {
                return getGatewayRoute(rs);
            }
        });
        return routeList;
    }

    private GatewayRoute getGatewayRoute(ResultSet rs) throws SQLException {
        GatewayRoute route = new GatewayRoute();
        route.setId(rs.getInt("id"));
        route.setUrl(rs.getString("url"));
        route.setPath(rs.getString("path"));
        Integer retry = rs.getInt("retryable");
        route.setRetryable(retry <= 0 ? 0 : retry);
        route.setRouteName(rs.getString("route_name"));
        route.setServiceId(rs.getString("service_id"));
        route.setPredicate(rs.getString("predicate"));
        route.setStripPrefix(rs.getInt("strip_prefix"));

        return route;
    }
}
